package com.qf.helloworld;

import com.qf.util.ConnectionUtil;
import com.rabbitmq.client.*;
import org.junit.Test;

import java.io.IOException;

public class Consumer {

    @Test
    public void consume() throws Exception {
        //1. 获取连接对象
        Connection connection = ConnectionUtil.getConnection();

        //2. 创建Channel
        Channel channel = connection.createChannel();

        //3. 再次创建队列.(要求两次创建队列时的属性,必须完全一致)
        channel.queueDeclare("hello_queue",true,false,false,null);
        // 预期406,404

        //4. 监听队列中的消息
        //4.1 queue: 消费者监听的队列名称
        //4.2 autoAck: 是否自动告诉RabbitMQ,消息已经消费完毕
        //4.3 consume: 消费者的回调函数,获取到消息后需要执行的操作
        channel.basicConsume("hello_queue",true,new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("消费者获取到hello_queue中的消息:" + new String(body));
            }
        });
        System.out.println("消费者开始监听消息!");
        //5. 避免程序停止
        System.in.read();
    }

}
